package com.tfswx.ocrengine.executor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.ocrengine.dto.OcrOutputDTO;
import com.tfswx.ocrengine.exception.AppException;
import com.tfswx.ocrengine.util.Base64Util;
import com.tfswx.ocrengine.util.HeheOcrUtils;
import com.tfswx.ocrengine.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Ricky
 * @date 2021/5/14
 */
@Slf4j
public class HeheOcrExecutor extends AbstractOcrExecutor {

    @Override
    public OcrOutputDTO run(String wjnr) throws EngineException {
        //        String url = "http://" + getEngineUrl() + "/icr/recognize_document";
        String url = "http://" + getHost() + "/icr/recognize_document_pos_multi";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        byte[] imgBytes = Base64Util.getByteArray(wjnr);
        HttpEntity<byte[]> httpEntity = new HttpEntity<>(imgBytes, headers);

        long startTime = System.currentTimeMillis();
        JSONObject response = HttpUtil.postForObject(url, httpEntity, JSONObject.class);
        log.info("耗时：" + (System.currentTimeMillis() - startTime));

        int errorCode = response.getIntValue("error_code");
        if (errorCode == 0) {
            JSONArray documents = response.getJSONArray("documents");
            if (documents.isEmpty()) {
                throw new AppException("识别结果为空");
            }

            JSONObject pageJsonObject = documents.getJSONObject(0);
            int width = 0;
            int height = 0;
            try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imgBytes)) {
                Thumbnails.Builder<? extends InputStream> builder = Thumbnails.of(byteArrayInputStream);
                builder.scale(1F);
                BufferedImage bufferedImage = builder.asBufferedImage();
                width = bufferedImage.getWidth();
                height = bufferedImage.getHeight();
            } catch (IOException e) {
                log.warn("合合引擎==>获取图片宽高失败：{}", e.getMessage());
            }

            pageJsonObject.put("height", height);
            pageJsonObject.put("orgHeight", height);
            pageJsonObject.put("orgWidth", width);
            pageJsonObject.put("width", width);

            JSONObject data = HeheOcrUtils.convert2Ali(documents);

            return data.toJavaObject(OcrOutputDTO.class);
        }
        throw new AppException(response.getString("error_msg"));
    }
}
